package it.francescogabbrielli.android.solidalapp.actions;

import java.util.List;

import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.response.ResponseActivity;
import it.francescogabbrielli.android.solidalapp.responseendpoint.Responseendpoint;
import it.francescogabbrielli.android.solidalapp.responseendpoint.model.Response;

/**
 * Send a response
 */
public class EndpointsInsertResponse extends Action {

	Response response;
	
	@Override
	public void execute() throws Exception {
		
		Response temp = getModel(Response.class);
		temp.setTimestamp(System.currentTimeMillis());
		
		Responseendpoint endpoint = EndpointsUtils.buildEndpoint(Responseendpoint.class);
		response = endpoint.insertResponse(temp).execute();
		setModel(response);
		Log.d(getClass().getSimpleName(), "Response sent: "+temp.getMessage());
		
	}

	@Override
	public void onError(String error) {
		app.setData(DataKey.RESPONSE, null);
		app.alert(app.getString(R.string.response_sent_error)+"\n"+error);
	}
	
	@Override
	public void onPostExecute() throws Exception {
		if (app.getData(DataKey.CHAT_RESPONSE)!=null)
			((List<?>) app.getData(DataKey.CHAT_RESPONSE)).clear();					
		Log.i(SolidalApp.TAG, "Response sent: "+response);
		app.setData(DataKey.RESPONSE, response);
		app.alert(R.string.response_sent_message);
		refireActivity(ResponseActivity.class);
	}

}
